<?php

class TShirtRequestController extends CController
{
	const PAGE_SIZE=10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='list';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

  /**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image
			// this is used by the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xEBF4FB,
			),
		);
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'list' and 'show' actions
				'actions'=>array('browse','view','captcha','unsubscribe'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','list','show','admin','newsletter'),
				'users'=>array('@'),
			),
			/*
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			*/
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow()
	{
    $this->layout='clean_side';
		$this->render('show',array('model'=>$this->loadTShirtRequest()));
	}

  /**
	 * Shows a particular model.
	 */
	public function actionView()
	{
    $this->layout = 'clean';
    $model = $this->loadTShirtRequest();
    $url = 'http://'.Yii::app()->request->serverName.CHtml::normalizeUrl(array('unsubscribe','id'=>$model->id,'key'=>$model->secure_key));
    // echo $url;
    $contact=new TContactForm;
		if(isset($_POST['TContactForm']))
		{
			$contact->attributes=$_POST['TContactForm'];
			if($contact->validate())
			{
        $subject = '[TrabajoProject] Oferta de trabajo de parte de '.$contact->name;
				$headers="From: {$contact->email}\r\nReply-To: {$contact->email}";
        $contact->body .= "\n\n------------------------------\n";
        $contact->body .= "Este mensaje ha sido enviado desde el buscador de TrabajoProject, \n";
        $contact->body .= "si ya has encontrado trabajo por favor entra en el siguiente enlace para \n";
        $contact->body .= "que dejemos de publicar tus datos:\n";
        $contact->body .= $url;
				// Un correo para TP.
        mail("buscador@trabajoproject.net",$subject,$contact->body,$headers);
        // Y otro para la persona
        if ($model->email) {
          mail($model->email,$subject,$contact->body,$headers);
        }
				Yii::app()->user->setFlash('contact','Tu mensaje ha sido enviado correctamente, gracias por ponerte en contacto con esta persona.');
				$this->refresh();
			}
		}
		$this->render('view',array('model'=>$model, 'contact'=>$contact));
	}

  public function actionUnsubscribe() {
    $this->layout = 'clean';
    $id = $_REQUEST['id'];
    $key = $_REQUEST['key'];
    $model = $this->loadTShirtRequest($id);
    if ($model && isset($_POST['UnsubscribeForm'])) {
      if ($model->found==0) {
        if (strlen($model->secure_key) > 0 && $model->secure_key == $key) {
          $model->found = 1;
          $headers="From: contacto@trabajoproject.net\r\nReply-To: contacto@trabajoproject.net";
          mail("buscador@trabajoproject.net",'UNO HA ENCONTRADO TRABAJO!!',$model->name." ha encontrado trabajo!",$headers);
          $model->save();
          Yii::app()->user->setFlash('unsubscribed','Te has dado de baja correctamente, desde ahora tus datos ya no apareceran en el buscador.');
        }
      }
    }
    $this->render('unsubscribe',array('model'=>$model));
  }

  private function buildSecureKeys() {
    $models = TShirtRequest::model()->findAll();
    foreach ($models as $model) {
      $model->secure_key=md5($model->name.$model->profession.$model->email.time());
      $model->save();
    }
  }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate()
	{
    $this->layout='clean_side';
		$model=new TShirtRequest;
		if(isset($_POST['TShirtRequest']))
		{
			$model->attributes=$_POST['TShirtRequest'];
			if($model->save())
				$this->redirect(array('show','id'=>$model->id));
		}
		$this->render('create',array('model'=>$model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{
    $this->layout='clean_side';
		$model=$this->loadTShirtRequest();
		if(isset($_POST['TShirtRequest']))
		{
			$model->attributes=$_POST['TShirtRequest'];
			if($model->save())
				$this->redirect(array('show','id'=>$model->id, 'return_page'=>$_REQUEST['return_page']));
		}
		$this->render('update',array('model'=>$model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadTShirtRequest()->delete();
			$this->redirect(array('list'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionList()
	{
    $this->layout='clean_side';
		$criteria=new CDbCriteria;
    
		$pages=new CPagination(TShirtRequest::model()->count($criteria));
		$pages->pageSize=self::PAGE_SIZE;
		$pages->applyLimit($criteria);

    $models=TShirtRequest::model()->findAll($criteria);

		$this->render('list',array(
			'models'=>$models,
			'pages'=>$pages,
		));
	}

  /**
	 * Browse all models.
	 */
	public function actionBrowse()
	{
    $profession = '';
    if (isset($_REQUEST['profession'])) {
      $profession = $_REQUEST['profession'];
      Yii::app()->session->add('profession', $profession);
    } elseif (isset(Yii::app()->session['profession'])) {
      $profession = Yii::app()->session['profession'];
    }
    $zone = '';
    if (isset($_REQUEST['zone'])) {
      $zone = $_REQUEST['zone'];
      Yii::app()->session->add('zone', $zone);
    } elseif (isset(Yii::app()->session['zone'])) {
      $zone = Yii::app()->session['zone'];
    }
    $this->layout = 'clean';
		$criteria=new CDbCriteria;
    $criteria->condition = 'found=0 AND profession is not null AND profession <> \'\'';
    if (strlen($profession)>0) {
      $criteria->addCondition("ucase(profession) like '%".strtoupper($profession)."%'");
    }
    if (strlen($zone)>0)
      $criteria->addCondition("ucase(zone) like '%".strtoupper($zone)."%'");
		// Show all emails
		/*
		$models_emails=TShirtRequest::model()->findAll();
		foreach ($models_emails as $me) {
			if (strlen($me->email) > 0)
				echo trim($me->email) . ', ';
		}
		echo '<br><br>';
		*/
		$pages=new CPagination(TShirtRequest::model()->count($criteria));
		$pages->pageSize=self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$models=TShirtRequest::model()->findAll($criteria);

		$this->render('browse',array(
			'models'=>$models,
			'pages'=>$pages,
      'profession'=>$profession,
      'zone'=>$zone,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
    $this->layout='clean_side';
		$this->processAdminCommand();

		$criteria=new CDbCriteria;

		$pages=new CPagination(TShirtRequest::model()->count($criteria));
		$pages->pageSize=self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$sort=new CSort('TShirtRequest');
		$sort->applyOrder($criteria);

		$models=TShirtRequest::model()->findAll($criteria);

		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadTShirtRequest($id=null)
	{
		if($this->_model===null)
		{
			if($id!==null || isset($_GET['id']))
				$this->_model=TShirtRequest::model()->findbyPk($id!==null ? $id : $_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Executes any command triggered on the admin page.
	 */
	protected function processAdminCommand()
	{
		if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete')
		{
			$this->loadTShirtRequest($_POST['id'])->delete();
			// reload the current page to avoid duplicated delete actions
			$this->refresh();
		}
	}
	
	public function actionNewsletter() {
		$models = Newsletter::model()->findAll();
		$emails = array();
		foreach ($models as $model) {
			$emails[] = $model->email;
		}
		echo implode(',', $emails);
	}
}
